package SnpDbHandling;

import SnpDbEntities.User;
import SnpDbEntities.UserPermissions;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 *
 * @author Łukasz 'byku' Guzik
 */
public class UserRecord
{
    private final User user;

    public UserRecord(User user)
    {
	this.user = user;
    }

    public final User getUser()
    {
	return user;
    }

    public static UserRecord getFromResultSet(ResultSet rs) throws SQLException
    {
	User userData = new User();
	userData.setId(rs.getInt("ID"));
	userData.setLogin(rs.getNString("Login"));
	userData.setPwdHash(rs.getNString("Password"));
	userData.setPermissions(UserPermissions.valueOf(rs.getNString("Permissions")));
	userData.setEnabled(rs.getBoolean("IsEnabled"));
	userData.setName(rs.getNString("Name"));
	userData.setEmail(rs.getNString("Email"));
	userData.setAbout(rs.getNString("About"));

	return new UserRecord(userData);
    }

    public void addToResultSet(ResultSet rs) throws SQLException
    {
	rs.updateNString("Login", user.getLogin());
	rs.updateNString("Permissions", user.getPermissions().toString());
	rs.updateNString("Password", user.getPwdHash());
	rs.updateBoolean("IsEnabled", user.isEnabled());
	rs.updateNString("Name", user.getName());
	rs.updateNString("Email", user.getEmail());
	if(user.getAbout() != null)
	{
	    rs.updateNString("About", user.getAbout());
	} else
	{
	    rs.updateNull("About");
	}
	if(!user.getPwdHash().equals("0"))
	    rs.updateNString("Password", user.getPwdHash());
    }

    public void updateInResultSet(ResultSet rs) throws SQLException
    {
	switch(user.getPermissions())
	{
	    case SUPER_ADMIN:
	    case ADMIN:
		rs.updateNString("Login", user.getLogin());
		rs.updateNString("Permissions", user.getPermissions().toString());

		if(!user.getPwdHash().equals("0"))
		    rs.updateNString("Password", user.getPwdHash());

	    case MODERATOR:
	    case NORMAL_USER:
		rs.updateBoolean("IsEnabled", user.isEnabled());
		rs.updateNString("Name", user.getName());
		rs.updateNString("Email", user.getEmail());
		if(user.getAbout() != null)
		{
		    rs.updateNString("About", user.getAbout());
		} else
		{
		    rs.updateNull("About");
		}
		if(!user.getPwdHash().equals("0"))
		    rs.updateNString("Password", user.getPwdHash());
	}
    }
}
